#include <stdio.h>
#include <stdbool.h>
#include <string.h>
#include "uthash.h"

// 定义一个结构体表示哈希表中的键值对
struct hash_node {
    char* key;
    char value;
    UT_hash_handle hh;  // 用于添加到哈希表中
};

bool wordPattern(char* pattern, char* s) {
     // 将 s 拆分成单词
    char* words[300];
    int word_count = 0;
    char* token = strtok(s, " ");
    while (token != NULL) {
        words[word_count++] = token;
        token = strtok(NULL, " ");
    }

    // 如果 pattern 的长度和单词数不一致，说明不匹配
    if (strlen(pattern) != word_count) return false;
    // 定义两个哈希表，用于存储字符和单词的映射
    char* char2WordMap[128] = {NULL};
    struct hash_node* word2CharMap = NULL;
     // 遍历 pattern 和单词，建立映射关系
    for (int i = 0; pattern[i] != '\0'; i++) {
        char c = pattern[i];
        char* word = words[i];

        struct hash_node *node;
        HASH_FIND_STR(word2CharMap, word, node);
        if ((char2WordMap[c] != NULL && strcmp(char2WordMap[c], word) != 0) ||
                (node != NULL && node->value != c)) {
            return false;
        }
        printf("-------1\n");
        // 更新 char2WordMap 和 word2CharMap 中的数据
        char2WordMap[c] = word;

        struct hash_node* word_node;
        HASH_FIND_STR(word2CharMap, word, word_node);
        if (word_node == NULL) {
            word_node = (struct hash_node*) malloc(sizeof(*word_node));
            word_node->key = word;
            word_node->value = c;
            HASH_ADD_STR(word2CharMap, key, word_node);
        }
    }

    // 释放哈希表结点所占用的内存
    struct hash_node* current_node, *tmp;
    HASH_ITER(hh, word2CharMap, current_node, tmp) {
        HASH_DEL(word2CharMap, current_node);
        free(current_node);
    }

    return true;
}